#include "serialgui.h"
#include "ui_serialgui.h"
#include <QThread>
SerialGui *SerialGui::_serialGuiObj = nullptr;


SerialGui::SerialGui(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SerialGui)
{
    ui->setupUi(this);


    ui->serialBaud->addItems(baudList);
    ui->serialCheck->addItems(parityCheckList);
    ui->serialStopBit->addItems(stopBitList);
    ui->serialDataBit->addItems(dataBitList);
    ui->inputTimeMs->setValidator(new QIntValidator(1,1000*1000,this));  //设置行输入框输入数字范围1~1000*1000


    getSerialInfo();

    ui->showText->document()->setMaximumBlockCount(50);
    setNumTx(0);
    setNumRx(0);
}

SerialGui::~SerialGui()
{
    delete ui;
}

void SerialGui::setPort(QString value)
{
    port = value;
}

void SerialGui::setBautdRate(QString value)
{
    baudRate = value;
}

void SerialGui::setParit(QString value)
{
    parit = value;
}

void SerialGui::setStopBit(QString value)
{
    stopBit = value;
}

void SerialGui::setDataBit(QString value)
{
    dataBit = value;
}

void SerialGui::getSerialInfo()
{
    ui->serialPort->clear();
    //获取可用的串口
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        ui->serialPort->addItem(info.portName());
    }

}

void SerialGui::setNumTx(unsigned long value)
{
    numTx = value;
}

unsigned long SerialGui::getNumTx()
{
    return numTx;
}

void SerialGui::setNumRx(unsigned long value)
{
    numRx = value;
}

unsigned long SerialGui::getNumRx()
{
    return numRx;
}

bool SerialGui::inputIsValid(QString input, QByteArray &out)
{
     StringToHex(input,out);
     if(out.length() == 0){
        return false;
     }else if((out.length()*2) == input.length()){
         return true;
     }
     return false;
}

void SerialGui::sendSerialDate(QString value)
{
    if(value.length() <= 0){
        return;
    }

    if( ui->enterCBox->checkState() == Qt::Checked){
            value.append("\r\n");
    }
    if( ui->hexCBox->checkState() == Qt::Unchecked){  //未选择十六进制
        setNumTx(getNumTx() + value.toLocal8Bit().length());
    }else if( ui->hexCBox->checkState() == Qt::Checked){
        QByteArray qByteArray;
        if(inputIsValid(value,qByteArray)){
            ui->sendText->setText(qByteArray.toHex());
        }else{
            QMessageBox::about(NULL, "提示", "输入16进制格式不正确");
            return;
        }
        setNumTx(getNumTx() + qByteArray.length());
    }
    emit serialGuiSerialSendSignals(value);
    ui->txLabel->setText("tx:" + QString::number(getNumTx()));
}

QString SerialGui::getPort()
{
    return port;
}

QString SerialGui::getBautdRate()
{
    return baudRate;
}

QString SerialGui::getParit()
{
    return parit;
}

QString SerialGui::getStopBit()
{
    return stopBit;
}

QString SerialGui::getDataBit()
{
    return dataBit;
}

void SerialGui::on_serialOpen_clicked()
{
    setPort(ui->serialPort->currentText());     //设置串口号
    setBautdRate(ui->serialBaud->currentText());    //设置波特率
    setParit(ui->serialCheck->currentText());   //设置校验
    setDataBit(ui->serialDataBit->currentText());   //设置数据位
    setStopBit(ui->serialStopBit->currentText());   //设置校验

    emit serialGuiSerialOpenSinles(getPort(),getBautdRate(),getParit(),getStopBit(),getDataBit());
}

void SerialGui::on_serialClose_clicked()
{
    ui->serialOpen->setEnabled(true);
    ui->serialClose->setEnabled(false);
    ui->serialSend->setEnabled(false);
    emit serialGuiSerialCloseSinles();
}

void SerialGui::serialGuiSerialOpenResultSlots(bool value)
{
    if(value != true){
         QMessageBox::about(NULL, "提示", "无法打开串口！");
         ui->serialOpen->setEnabled(true);
         ui->serialClose->setEnabled(false);
         ui->serialSend->setEnabled(false);
         return;
    }
    ui->serialOpen->setEnabled(false);
    ui->serialClose->setEnabled(true);
    ui->serialSend->setEnabled(true);
    qDebug()<<"gui线程 ID:" <<QThread::currentThreadId();
}

void SerialGui::serialGuiShowText(QByteArray value)
{
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString currentDateStr = currentDateTime.toString("[yyyy.MM.dd hh:mm:ss ddd] ");
    ui->showText->append("<font color=\"#FF0000\">" + currentDateStr + "</font> ");
    ui->showText->append("<font color=\"#000000\">" + value + "</font> ");

    if( ui->hexCBox->checkState() == Qt::Unchecked){  //未选择十六进制接收
        setNumRx(getNumRx() + QString(value).toLocal8Bit().length());
    }else if( ui->hexCBox->checkState() == Qt::Checked){
        setNumRx(getNumRx() + value.length() / 2);
    }
    ui->rxLable->setText("rx:" + QString::number(getNumRx()));
}

void SerialGui::on_serialSend_clicked()
{
    QString value = ui->sendText->toPlainText();
    sendSerialDate(value);

}

void SerialGui::on_hexCBox_stateChanged(int arg1)
{
    if(Qt::Checked == arg1){
        emit serialGuiSerialHexSignals(true);
    }else{
        emit serialGuiSerialHexSignals(false);
    }
}

void SerialGui::isTimerSendSlots(){
    QString value = ui->sendText->toPlainText();
    sendSerialDate(value);

}

void SerialGui::on_isTimeSendCBox_stateChanged(int arg1)
{
   if(arg1 == 2){//选择定时发送
        if(ui->serialOpen->isEnabled() == true){
            return;         //此时串口未打开
        }

        isTimerSend = new QTimer();
        connect(isTimerSend, &QTimer::timeout, this, &SerialGui::isTimerSendSlots);
        if(ui->inputTimeMs->text().toInt() >= 1){
            isTimerSend->start(ui->inputTimeMs->text().toInt());    //启动定时发送
        }
   }else{
       if(ui->serialOpen->isEnabled() == true){
            return;
       }
       isTimerSend->stop();
       delete isTimerSend;
   }
}

void SerialGui::StringToHex(QString str, QByteArray &senddata)
{
    int hexdata,lowhexdata;
    int hexdatalen = 0;
    int len = str.length();
    senddata.resize(len/2);
    char lstr,hstr;
    for(int i=0; i<len; )
    {
        //char lstr,
        hstr=str[i].toLatin1();
        if(hstr == ' ')
        {
            i++;
            continue;
        }
        i++;
        if(i >= len)
            break;
        lstr = str[i].toLatin1();
        hexdata = ConvertHexChar(hstr);
        lowhexdata = ConvertHexChar(lstr);
        if((hexdata == 16) || (lowhexdata == 16))
            break;
        else
            hexdata = hexdata*16+lowhexdata;
        i++;
        senddata[hexdatalen] = (char)hexdata;
        hexdatalen++;
    }
    senddata.resize(hexdatalen);
}
char SerialGui::ConvertHexChar(char ch)
{
    if((ch >= '0') && (ch <= '9'))
            return ch-0x30;
        else if((ch >= 'A') && (ch <= 'F'))
            return ch-'A'+10;
        else if((ch >= 'a') && (ch <= 'f'))
            return ch-'a'+10;
        else return (-1);
}

void SerialGui::on_clearBtn_clicked()
{
    ui->sendText->clear();
    ui->showText->clear();
    setNumRx(0);
    setNumTx(0);
    ui->rxLable->setText("rx:" + QString::number(getNumRx()));
    ui->txLabel->setText("tx:" + QString::number(getNumTx()));
}
